package api;

import org.apache.kudu.client.*;

public class TableActionDemo {

   KuduClient.KuduClientBuilder builder = new KuduClient.KuduClientBuilder("linux122")
           .defaultSocketReadTimeoutMs(5000);
   KuduClient client = builder.build();
   String tableName = "school";

    public static void main(String[] args) {
        TableActionDemo demo = new TableActionDemo();
        demo.insert();
        demo.select();
        demo.update();
        demo.select();
        demo.delete();
        demo.select();
    }

   public void insert() {
       try {
           KuduTable table = client.openTable(tableName);
           KuduSession kuduSession = client.newSession();
           kuduSession.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH);
           Insert insert = table.newInsert();

           insert.getRow().addInt("id", 1);
           insert.getRow().addString("name", "bd");
           insert.getRow().addLong("create_time", System.currentTimeMillis());

           kuduSession.flush();
           kuduSession.apply(insert);
           kuduSession.close();
       } catch (KuduException e) {
           e.printStackTrace();
       }
   }

   public void update() {
       try {
           KuduTable table = client.openTable(tableName);
           KuduSession kuduSession = client.newSession();
           kuduSession.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH);
           Update update = table.newUpdate();
           PartialRow row = update.getRow();
           row.addInt("id", 1);
           row.addString("name", "qh");
           kuduSession.apply(update);
           kuduSession.close();
       } catch (KuduException e) {
           e.printStackTrace();
       }
   }

   public void select() {
       try {
           KuduTable table = client.openTable(tableName);
           KuduScanner scanner = client.newScannerBuilder(table).build();
           while(scanner.hasMoreRows()) {
               for (RowResult result: scanner.nextRows()) {
                   long id = result.getLong("id");
                   String name = result.getString("name");
                   System.out.println("id:" + id + "...name:" + name);
               }
           }
       } catch (KuduException e) {
           e.printStackTrace();
       }
   }

   public void delete() {
       try {
           KuduTable table = client.openTable(tableName);
           KuduSession kuduSession = client.newSession();
           kuduSession.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH);
           Delete delete = table.newDelete();
           PartialRow row = delete.getRow();
           row.addInt("id", 1);
           kuduSession.flush();
           kuduSession.apply(delete);

           kuduSession.close();

       } catch (KuduException e) {
           e.printStackTrace();
       }
   }


}
